package com.ruoyi.warn.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.constant.BusinessConstant;
import com.ruoyi.common.core.domain.dto.EventPlan;
import com.ruoyi.common.core.domain.vo.UserInfoVo;
import com.ruoyi.common.core.service.UserDrugBusinessService;
import com.ruoyi.common.enums.UserBusinessSubType;
import com.ruoyi.common.enums.UserDrugType;
import com.ruoyi.common.enums.UserEventType;
import com.ruoyi.event.domain.EventYzwfxy;
import com.ruoyi.event.mapper.EventYzwfxyMapper;
import com.ruoyi.event.service.IEventJcjhService;
import com.ruoyi.user.domain.UserInfo;
import com.ruoyi.user.mapper.UserInfoMapper;
import com.ruoyi.warn.domain.vo.*;
import com.ruoyi.warn.mapper.WarnMapper;
import com.ruoyi.warn.service.IWarnService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 智能预警Service业务层处理
 *
 * @author xiaohao
 * @date 2023-02-10
 */
@RequiredArgsConstructor
@Service
public class WarnServiceImpl implements IWarnService {

    private final WarnMapper warnMapper;
    private final UserInfoMapper userInfoMapper;
    private final EventYzwfxyMapper yzwfxyMapper;
    private final UserDrugBusinessService userDrugBusinessService;
    private final IEventJcjhService eventJcjhService;

    @Override
    public FxryNumsVo fxryNums() {
        return warnMapper.fxryNums();
    }

    @Override
    public List<FxryDetailVo> fxryDetails() {
        return warnMapper.fxryDetails();
    }

    @Override
    public int sjskzrs() {
        LambdaQueryWrapper<UserInfo> wrapper = Wrappers.lambdaQuery(UserInfo.class);
        wrapper.lt(UserInfo::getCreateTime, DateUtil.date());
        return Convert.toInt(userInfoMapper.selectCount(wrapper));
    }

    @Override
    public int sjskXzrsByMonth(String date) {
        return warnMapper.sjskXzrsByMonth(date);
    }

    @Override
    public List<DayStatisticsVo> sjskbyxzrsStatisticsByMonth(String date) {
        return warnMapper.sjskbyxzrsStatistics(date);
    }

    @Override
    public List<RyDetailVo> sjskXzrsDetailByMonth(String date) {
        return warnMapper.sjskXzrsDetailByMonth(date);
    }

    @Override
    public int wfxyzrs() {
        LambdaQueryWrapper<EventYzwfxy> wrapper = Wrappers.lambdaQuery(EventYzwfxy.class);
        wrapper.lt(EventYzwfxy::getCreateTime, DateUtil.date());
        return Convert.toInt(yzwfxyMapper.selectCount(wrapper));
    }

    @Override
    public int wfxyxzrsByMonth(String date) {
        return warnMapper.wfxyxzrsByMonth(date);
    }

    @Override
    public List<DayStatisticsVo> yzwfxybyxzrsStatisticsByMonth(String date) {
        return warnMapper.yzwfxybyxzrsStatisticsByMonth(date);
    }

    @Override
    public List<RyDetailVo> yzwfxyxzrsDetailByMonth(String date) {
        List<RyDetailVo> results = warnMapper.wfxyxzrsDetailByMonth(date);
        if (CollUtil.isNotEmpty(results)) {
            results.forEach(t -> {
                UserInfoVo info = userDrugBusinessService.queryById(t.getUserId());
                t.setName(info.getName());
                t.setIdno(info.getIdno());
                t.setArea(info.getArea());
                t.setMobile(info.getMobile());
                t.setType(info.getBusinessSubType().getUserType());
            });
        }
        return results;
    }

    @Override
    public Integer cqwbdrsNumsByMonth(String date) {
        return warnMapper.cqwbdrsNumsByMonth(date);
    }

    @Override
    public List<DayStatisticsVo> cqwbdrsStatisticsByMonth(String date) {
        return warnMapper.cqwbdrsStatisticsByMonth(date);
    }

    @Override
    public List<RyDetailVo> cqwbdrsDetailByDay(String date) {
        return warnMapper.cqwbdrsDetailByDay(date);
    }

    @Override
    public List<DayStatisticsVo> qjcsryStatisticsByMonth(String date) {
        return warnMapper.qjcsryStatisticsByMonth(date);
    }

    @Override
    public List<RyDetailVo> qjcsryDetailByDay(String date) {
        return warnMapper.qjcsryDetailByDay(date);
    }

    @Override
    public List<JszsfdxStatisticsVo> jszsfdxStatistics() {
        return warnMapper.jszsfdxStatistics();
    }

    @Override
    public List<RyDetailVo> jszsfdxWdxryDetail() {
        return warnMapper.jszsfdxWdxryDetail();
    }

    @Override
    public List<QdyjStatisticsVo> qdyjStatistics() {
        return warnMapper.qdyjStatistics();
    }

    @Override
    public List<RyDetailVo> qdyjDetail() {
        return warnMapper.qdyjDetail();
    }

    @Override
    public Integer njyjNum() {
        return warnMapper.njyjNum();
    }

    @Override
    public List<RyDetailVo> njyjDetail(String type) {
        switch (type) {
            case BusinessConstant.njyjcxlx.NJYJRYXQ: // 尿检预警人员详情
                return warnMapper.njyjryxq();
            case BusinessConstant.njyjcxlx.CQWNJRYXQ: // 超期未尿检人员详情
                // 生成3年内的周期
                List<UserInfo> sjsks = userInfoMapper.selectList();
                List<RyDetailVo> results = Lists.newArrayList();
                sjsks.forEach(user -> {
                    List<EventPlan> eventPlans = eventJcjhService.generatePlans(UserEventType.EVENT_NJ, UserDrugType.getUserType(user.getType(), UserBusinessSubType.DRUG_SJSK), user.getJdsj(), true);
                    if (CollUtil.isNotEmpty(eventPlans)) {
                        List<String> cycleRanges = eventPlans.stream().map(EventPlan::getRangeStr).collect(Collectors.toList());
                        boolean sfcqwj = warnMapper.cqwnjryxq(cycleRanges); // 是否超期未检
                        if (sfcqwj) {
                            RyDetailVo userDetailVo = BeanUtil.copyProperties(user, RyDetailVo.class);
                            userDetailVo.setUserId(user.getId());
                            userDetailVo.setLastTime("-");
                            userDetailVo.setTime(DateUtil.format(user.getBdrq(), "yyyy-MM-dd"));
                            results.add(userDetailVo);
                        }
                    }
                });
                return results;
            case BusinessConstant.njyjcxlx.BZQYNJRYXQ: // 本周期已尿检人员详情
                return warnMapper.bzqynjryxq();
            default:
                throw new RuntimeException("未知的尿检查询类型");
        }
    }

    @Override
    public List<JfyjStatisticsVo> jfyjStatistics() {
        return warnMapper.jfyjStatistics();
    }

    @Override
    public List<RyDetailVo> jfyjDetail() {
        return warnMapper.jfyjDetail();
    }

    @Override
    public Integer mftjNum() {
        return warnMapper.mftjNum();
    }

    @Override
    public List<RyDetailVo> mftjDetail() {
        return warnMapper.mftjDetail();
    }

    @Override
    public BfyjStatisticsVo bfyjStatistics() {
        return warnMapper.bfyjStatistics();
    }

    @Override
    public List<RyDetailVo> bfyjDetail() {
        return warnMapper.bfyjDetail();
    }

    @Override
    public Integer fwtcyjNum() {
        return warnMapper.fwtcyjNum();
    }

    @Override
    public List<FwTcDetailVo> fwtcyjDetail(String type, String mode) {
        return warnMapper.fwtcyjDetail(type, mode);
    }

    @Override
    public GzrzNumsVo gzrzNums(Long memberId) {
        GzrzNumsVo gzrzNumsVo = warnMapper.gzrzNums(memberId);
        List<RyDetailVo> bqwnjList = getBqwnjListByMemberId(memberId);
        gzrzNumsVo.setBqwnj(bqwnjList.size());
        return gzrzNumsVo;
    }

    @Override
    public List<UserInfoVo> gzrzCqwbdrList(Long memberId) {
        return userDrugBusinessService.queryByIds(warnMapper.gzrzCqwbdrList(memberId).stream().map(RyDetailVo::getUserId).collect(Collectors.toList()));
    }

    @Override
    public List<UserInfoVo> gzrzBqwnjList(Long memberId) {
        return userDrugBusinessService.queryByIds(getBqwnjListByMemberId(memberId).stream().map(RyDetailVo::getUserId).collect(Collectors.toList()));
    }

    @Override
    public List<UserInfoVo> gzrzWcryList(Long memberId) {
        return userDrugBusinessService.queryByIds(warnMapper.gzrzWcryList(memberId).stream().map(RyDetailVo::getUserId).collect(Collectors.toList()));
    }

    @Override
    public List<UserInfoVo> gzrzByptwfxyList(Long memberId) {
        return userDrugBusinessService.queryByIds(warnMapper.gzrzByptwfxyList(memberId).stream().map(RyDetailVo::getUserId).collect(Collectors.toList()));
    }

    @Override
    public List<UserInfoVo> gzrzByYzwfxyList(Long memberId) {
        return userDrugBusinessService.queryByIds(warnMapper.gzrzByYzwfxyList(memberId).stream().map(RyDetailVo::getUserId).collect(Collectors.toList()));
    }

    /**
     * 获取本期未尿检人员列表
     */
    public List<RyDetailVo> getBqwnjListByMemberId(Long memberId) {
        List<UserInfo> sjsks = userInfoMapper.selectList(
            Wrappers.<UserInfo>lambdaQuery()
                .in(UserInfo::getType, UserBusinessSubType.DRUG_SJSK.getDrugTypeList())
                .eq(UserInfo::getFzr, memberId)
        );
        List<RyDetailVo> results = Lists.newArrayList();
        sjsks.forEach(user -> {
            // 生成周期
            List<EventPlan> eventJcPlans = eventJcjhService.generatePlans(UserEventType.EVENT_NJ, UserDrugType.getUserType(user.getType(), UserBusinessSubType.DRUG_SJSK), user.getJdsj(), true);
            if (CollUtil.isNotEmpty(eventJcPlans)) {
                List<String> cycleRanges = eventJcPlans.stream().map(EventPlan::getRangeStr).collect(Collectors.toList());
                boolean sfcqwj = warnMapper.cqwnjryxq(cycleRanges); // 是否超期未检
                if (sfcqwj) {
                    RyDetailVo userDetailVo = BeanUtil.copyProperties(user, RyDetailVo.class);
                    userDetailVo.setUserId(user.getId());
                    userDetailVo.setLastTime("-");
                    userDetailVo.setTime(DateUtil.format(user.getJdsj(), "yyyy-MM-dd"));
                    results.add(userDetailVo);
                }
            }
        });
        return results;
    }

    /**
     * 获取本期未尿检人员列表
     */
    @Override
    public List<RyDetailVo> getBqwnjList() {
        List<UserInfo> sjsks = userInfoMapper.selectList(
            Wrappers.<UserInfo>lambdaQuery()
                .in(UserInfo::getType, UserBusinessSubType.DRUG_SJSK.getDrugTypeList())
                .isNotNull(UserInfo::getFzr)
        );
        List<RyDetailVo> results = Lists.newArrayList();
        sjsks.forEach(user -> {
            // 生成周期
            List<EventPlan> eventJcPlans = eventJcjhService.generatePlans(UserEventType.EVENT_NJ, UserDrugType.getUserType(user.getType(), UserBusinessSubType.DRUG_SJSK), user.getJdsj(), true);
            if (CollUtil.isNotEmpty(eventJcPlans)) {
                List<String> cycleRanges = eventJcPlans.stream().map(EventPlan::getRangeStr).collect(Collectors.toList());
                boolean sfcqwj = warnMapper.cqwnjryxq(cycleRanges); // 是否超期未检
                if (sfcqwj) {
                    RyDetailVo userDetailVo = BeanUtil.copyProperties(user, RyDetailVo.class);
                    userDetailVo.setUserId(user.getId());
                    userDetailVo.setLastTime("-");
                    userDetailVo.setTime(DateUtil.format(user.getJdsj(), "yyyy-MM-dd"));
                    results.add(userDetailVo);
                }
            }
        });
        return results;
    }

    /**
     * 获取本期已经尿检人员列表
     */
    @Override
    public List<RyDetailVo> getBqynjList() {
        List<UserInfo> sjsks = userInfoMapper.selectList(
            Wrappers.<UserInfo>lambdaQuery()
                .in(UserInfo::getType, UserBusinessSubType.DRUG_SJSK.getDrugTypeList())
                .isNotNull(UserInfo::getFzr)
        );
        List<RyDetailVo> results = Lists.newArrayList();
        sjsks.forEach(user -> {
            // 生成周期
            List<EventPlan> eventJcPlans = eventJcjhService.generatePlans(UserEventType.EVENT_NJ, UserDrugType.getUserType(user.getType(), UserBusinessSubType.DRUG_SJSK), user.getJdsj(), true);
            if (CollUtil.isNotEmpty(eventJcPlans)) {
                List<String> cycleRanges = eventJcPlans.stream().map(EventPlan::getRangeStr).collect(Collectors.toList());
                boolean sfcqwj = warnMapper.cqwnjryxq(cycleRanges); // 是否超期未检
                if (!sfcqwj) {
                    RyDetailVo userDetailVo = BeanUtil.copyProperties(user, RyDetailVo.class);
                    userDetailVo.setUserId(user.getId());
                    userDetailVo.setLastTime("-");
                    userDetailVo.setTime(DateUtil.format(user.getJdsj(), "yyyy-MM-dd"));
                    results.add(userDetailVo);
                }
            }
        });
        return results;
    }

    /**
     * 获取本期未尿检人员列表
     */
    @Override
    public List<RyDetailVo> getBqwnjListByUsers(List<UserInfo> sjsks) {
        List<RyDetailVo> results = Lists.newArrayList();
        if (CollUtil.isNotEmpty(sjsks)) {
            sjsks.forEach(user -> {
                // 生成周期
                List<EventPlan> eventJcPlans = eventJcjhService.generatePlans(UserEventType.EVENT_NJ, UserDrugType.getUserType(user.getType(), UserBusinessSubType.DRUG_SJSK), user.getJdsj(), true);
                if (CollUtil.isNotEmpty(eventJcPlans)) {
                    List<String> cycleRanges = eventJcPlans.stream().map(EventPlan::getRangeStr).collect(Collectors.toList());
                    boolean sfcqwj = warnMapper.cqwnjryxq(cycleRanges); // 是否超期未检
                    if (sfcqwj) {
                        RyDetailVo userDetailVo = BeanUtil.copyProperties(user, RyDetailVo.class);
                        userDetailVo.setUserId(user.getId());
                        userDetailVo.setLastTime("-");
                        userDetailVo.setTime(DateUtil.format(user.getJdsj(), "yyyy-MM-dd"));
                        results.add(userDetailVo);
                    }
                }
            });
        }
        return results;
    }
}
